package com.example.xlmkotlinwanandroid.data.remote

import android.os.Build
import com.example.xlmkotlinwanandroid.BuildConfig
import com.example.xlmkotlinwanandroid.util.ConstantUtil
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 *  author : cailei
 *  date : 2022/3/18
 *  description : build retrofit
 */

private const val timeoutRead = 30   //In seconds
private const val contentType = "Content-Type"
private const val contentTypeValue = "application/json"
private const val timeoutConnect = 30   //In seconds


object RetrofitGenerator {
    private val okHttpBuilder: OkHttpClient.Builder = OkHttpClient.Builder()
    private val retrofit: Retrofit

    private val logger: HttpLoggingInterceptor
        get() {
            val httpLogger = HttpLoggingInterceptor()
            if (BuildConfig.DEBUG) {
                httpLogger.level = HttpLoggingInterceptor.Level.BODY
            }
            return httpLogger
        }

    init {
        okHttpBuilder.addInterceptor(logger)
        okHttpBuilder.connectTimeout(timeoutConnect.toLong(), TimeUnit.SECONDS)
        okHttpBuilder.readTimeout(timeoutRead.toLong(), TimeUnit.SECONDS)
        val client = okHttpBuilder.build()
        retrofit = Retrofit.Builder().baseUrl(ConstantUtil.BASE_URL).client(client)
            .addConverterFactory(GsonConverterFactory.create()).build()
    }

    fun <S> createService(serviceClass: Class<S>): S {
        return retrofit.create(serviceClass)
    }
}